﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace MT.EnumTool
{
    /// <summary>
    /// EnumHelper
    /// </summary>
    public class EnumHelper
    {
        #region 枚举操作

        /// <summary>
        /// 根据枚举值获取描述
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetDescriptionByEnum(Enum enumValue)
        {
            try
            {
                string value = enumValue.ToString();
                FieldInfo field = enumValue.GetType().GetField(value);
                if (field == null)
                    return null;

                object[] objs = field?.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
                if (objs?.Length == 0)    //当描述属性没有时，直接返回名称
                    return value;

                DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
                return descriptionAttribute.Description;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 根据描述获取枚举值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="description"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static T GetEnumByDescription<T>(string description) where T : Enum
        {
            if(string.IsNullOrEmpty(description))
                return default(T);

            FieldInfo[] fields = typeof(T).GetFields();
            foreach (FieldInfo field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
                if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }

            throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
        }

        /// <summary>
        /// 根据字符串获取枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T StringToEnum<T>(string str)
        {
            return (T)Enum.Parse(typeof(T), str);
        }

        #endregion

    }
}
